package com.jeeplus.mob.payUtile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;

public class PayCommonUtil
{
  public static boolean isTenpaySign(String characterEncoding, SortedMap<Object, Object> packageParams, String API_KEY)
  {
    StringBuffer sb = new StringBuffer();
    Set es = packageParams.entrySet();
    Iterator it = es.iterator();
    while (it.hasNext())
    {
      Entry entry = (Entry)it.next();
      String k = (String)entry.getKey();
      String v = (String)entry.getValue();
      if ((!"sign".equals(k)) && (v != null) && (!"".equals(v))) {
        sb.append(k + "=" + v + "&");
      }
    }
    sb.append("key=" + API_KEY);
    

    String mysign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toLowerCase();
    String tenpaySign = ((String)packageParams.get("sign")).toLowerCase();
    

    return tenpaySign.equals(mysign);
  }
  
  public static String createSign(String characterEncoding, SortedMap<Object, Object> packageParams, String API_KEY)
  {
    StringBuffer sb = new StringBuffer();
    Set es = packageParams.entrySet();
    Iterator it = es.iterator();
    while (it.hasNext())
    {
      Entry entry = (Entry)it.next();
      String k = (String)entry.getKey();
      String v = (String)entry.getValue();
      if ((v != null) && (!"".equals(v)) && (!"sign".equals(k)) && (!"key".equals(k))) {
        sb.append(k + "=" + v + "&");
      }
    }
    sb.append("key=" + API_KEY);
    String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
    return sign;
  }
  
  public static String getRequestXml(Map<String, String> parameters)
  {
    StringBuffer sb = new StringBuffer();
    sb.append("<xml>");
    Set es = parameters.entrySet();
    Iterator it = es.iterator();
    while (it.hasNext())
    {
      Entry entry = (Entry)it.next();
      String k = (String)entry.getKey();
      String v = (String)entry.getValue();
      if (("attach".equalsIgnoreCase(k)) || ("body".equalsIgnoreCase(k)) || ("sign".equalsIgnoreCase(k))) {
        sb.append("<" + k + ">" + v + "</" + k + ">");
      } else {
        sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");
      }
    }
    sb.append("</xml>");
    return sb.toString();
  }
  
  public static int buildRandom(int length)
  {
    int num = 1;
    double random = Math.random();
    if (random < 0.1D) {
      random += 0.1D;
    }
    for (int i = 0; i < length; i++) {
      num *= 10;
    }
    return (int)(random * num);
  }
  
  public static String getCurrTime()
  {
    Date now = new Date();
    SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    String s = outFormat.format(now);
    return s;
  }
}
